<template>
  <s-layout :title="product.name || '产品详情'">
    <view class="detail-container">
      <scroll-view scroll-y class="content-scroll">
        <!-- 商品主图 -->
        <image class="product-main-image" :src="product.image" mode="widthFix" />

        <!-- 商品信息 -->
        <view class="product-info-card">
          <view class="product-name">{{ product.name }}</view>
          <view class="product-desc">{{ product.description }}</view>
          <view class="product-price">¥{{ currentPrice }}</view>
        </view>

        <!-- 规格选择 -->
        <view class="spec-card" v-if="product.specs && product.specs.length > 0">
          <view class="sku-tip" v-if="hasDisabledOptions">
            ℹ️ 灰色划线选项与其他规格组合不可用
          </view>
          <view class="spec-group" v-for="spec in product.specs" :key="spec.id">
            <view class="spec-group-header">
              <view class="spec-group-name">
                {{ spec.name }}
                <text class="disabled-count" v-if="getDisabledCount(spec) > 0">
                  ({{ getAvailableCount(spec) }} 个可选)
                </text>
              </view>
            </view>
            <view class="spec-options">
              <button
                class="spec-option"
                v-for="option in spec.options"
                :key="option.id"
                :class="{ 
                  active: isOptionSelected(spec, option),
                  disabled: isOptionDisabled(spec, option)
                }"
                :disabled="isOptionDisabled(spec, option)"
                @click="selectSpec(spec, option)"
              >
                <view class="option-name">{{ option.name }}</view>
                <view class="option-price" v-if="option.price && option.price > 0">
                  +¥{{ option.price }}
                </view>
              </button>
            </view>
          </view>
        </view>

        <!-- 加料选择 -->
        <view class="spec-card" v-if="product.accessories && product.accessories.length > 0">
          <view class="spec-group">
            <view class="spec-group-name">加料选项</view>
            <view class="spec-options">
              <button
                class="spec-option"
                v-for="accessory in product.accessories"
                :key="accessory.code"
                :class="{ active: selectedAccessories.includes(accessory.code) }"
                @click="toggleAccessory(accessory)"
              >
                <view class="option-name">{{ accessory.name }}</view>
                <view class="option-price">+¥{{ accessory.price }}</view>
              </button>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 底部操作栏 -->
      <view class="bottom-bar">
        <view class="price-section">
          <text>¥</text>
          <text class="price-value">{{ currentPrice }}</text>
        </view>
        <button class="add-to-cart-btn" @click="addToCart">加入购物车</button>
      </view>
    </view>
  </s-layout>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import sheep from '@/sheep';
import { onLoad } from '@dcloudio/uni-app';
import { 
  getSpecKey, 
  getOptionKey, 
  findOption, 
  safeParseFloat, 
  buildSpecsText, 
  parsePrice,
  parseOriginalPrice,
  buildFullSelectedSpecs,
  stripHtmlTags
} from './common/product-utils.js';

const cateringStore = sheep.$store('catering');

const product = reactive({
  id: 0,
  name: '',
  image: '',
  description: '',
  basePrice: 0,
  originalPrice: 0,
  specs: [],
  accessories: [],
  skuList: []  // 添加SKU列表
});

const selectedSpecs = reactive({});
const selectedAccessories = ref([]);

onLoad(async (options) => {
  const passedProductId = options.productId || options.id;
  const passedShopId = options.shopId;

  if (!passedProductId) {
    uni.showToast({ title: '缺少商品信息', icon: 'error' });
    setTimeout(() => sheep.$router.back(), 1500);
    return;
  }
  
  const store = cateringStore.storeInfo;
  const shopId = passedShopId || (store && (store.shopId || store.id));
  if (!shopId) {
    uni.showToast({ title: '请先选择门店', icon: 'error' });
    setTimeout(() => sheep.$router.back(), 1500);
    return;
  }

  console.log('【奈雪】加载商品详情:', { productId: passedProductId, shopId });
  
  uni.showLoading({ title: '加载中...' });
  try {
    const res = await sheep.$api.catering.getProductDetail(passedProductId, shopId);
    uni.hideLoading();
    
    if ((res.code === 0 || res.code === 200) && res.data) {
      parseProductData(res.data, options);
    } else {
      uni.showToast({ title: '加载商品失败', icon: 'none' });
      setTimeout(() => sheep.$router.back(), 1500);
    }
  } catch (error) {
    uni.hideLoading();
    console.error('【奈雪】加载商品详情失败:', error);
    uni.showToast({ title: '加载商品失败', icon: 'error' });
    setTimeout(() => sheep.$router.back(), 1500);
  }
});

// 解析奈雪商品数据
function parseProductData(apiData, options) {
  // 基础信息
  product.id = apiData.product_id || apiData.productId || options.productId;
  product.name = apiData.product_name || apiData.productName || options.name || '';
  product.image = apiData.product_img || apiData.productImg || '';
  // ✅ 处理HTML格式的描述
  const rawDesc = apiData.product_description || apiData.productDescription || '';
  product.description = stripHtmlTags(rawDesc);
  product.basePrice = parsePrice(apiData);
  product.originalPrice = parseOriginalPrice(apiData);

  console.log('【奈雪】售价:', product.basePrice, '原价:', product.originalPrice);

  const details = apiData.details || apiData;
  
  // 解析奈雪规格
  if (details.spu_specs) {
    product.specs = details.spu_specs.map(spec => ({
      id: spec.code,
      name: spec.name,
      options: (spec.values || []).map(val => ({
        id: val.code,
        name: val.name,
        price: safeParseFloat(val.price),
        checked: val.checked === 1
      }))
    }));
  }

  // 加料
  product.accessories = details.accessories || [];
  
  // 保存SKU列表
  product.skuList = details.sku_infos || [];
  
  console.log('【奈雪】SKU列表:', product.skuList.length, '个');
  
  // 【临时调试】输出所有SKU详情
  console.log('【奈雪】🔍 所有SKU详情:');
  product.skuList.forEach((sku, index) => {
    const specs = sku.specs.map(s => `${s.name}=${s.spec_name}(${s.spec_code})`).join(', ');
    console.log(`  SKU${index + 1}: ${sku.code} | ${specs} | 价格:${sku.salePrice}/${sku.price}`);
  });

  // 初始化默认选中
  initializeDefaultSelection();
}

// 初始化默认选中
function initializeDefaultSelection() {
  product.specs.forEach(spec => {
    if (!spec.options || spec.options.length === 0) return;
    
    const defaultOption = spec.options.find(opt => opt.checked) || spec.options[0];
    selectedSpecs[getSpecKey(spec)] = getOptionKey(defaultOption);
  });
}

// 判断选项是否被选中
function isOptionSelected(spec, option) {
  return selectedSpecs[getSpecKey(spec)] === getOptionKey(option);
}

// 判断选项是否被禁用
function isOptionDisabled(spec, option) {
  // 奈雪需要检查SKU兼容性
  if (!product.skuList || product.skuList.length === 0) {
    return false;
  }
  
  const specKey = getSpecKey(spec);
  const optionKey = getOptionKey(option);
  
  // 创建临时选择（假设选择了当前选项）
  const tempSelected = { ...selectedSpecs, [specKey]: optionKey };
  
  // 检查是否存在包含这个选择的SKU
  const hasCompatibleSku = product.skuList.some(sku => {
    if (!sku.specs) return false;
    
    // 检查当前临时选择是否与某个SKU兼容
    return Object.keys(tempSelected).every(selectedSpecCode => {
      const selectedOptionCode = tempSelected[selectedSpecCode];
      const skuSpec = sku.specs.find(s => s.code === selectedSpecCode);
      
      // 如果SKU中没有这个规格，或者规格值不匹配，返回false
      return skuSpec && skuSpec.spec_code === selectedOptionCode;
    });
  });
  
  return !hasCompatibleSku;
}

// 获取规格组中禁用选项的数量
function getDisabledCount(spec) {
  return spec.options.filter(option => isOptionDisabled(spec, option)).length;
}

// 获取规格组中可用选项的数量
function getAvailableCount(spec) {
  return spec.options.filter(option => !isOptionDisabled(spec, option)).length;
}

// 选择规格
function selectSpec(spec, option) {
  const specKey = getSpecKey(spec);
  const optionKey = getOptionKey(option);
  
  selectedSpecs[specKey] = optionKey;
  console.log('【奈雪】当前已选规格:', JSON.parse(JSON.stringify(selectedSpecs)));
  
  // 检查并自动调整不兼容的规格
  product.specs.forEach(otherSpec => {
    const otherSpecKey = getSpecKey(otherSpec);
    if (otherSpecKey === specKey) return; // 跳过当前规格
    
    const currentOptionKey = selectedSpecs[otherSpecKey];
    if (!currentOptionKey) return; // 还没选择
    
    // 找到当前选择的选项对象
    const currentOption = otherSpec.options.find(opt => getOptionKey(opt) === currentOptionKey);
    if (!currentOption) return;
    
    // 检查这个选项是否现在变成不兼容了
    if (isOptionDisabled(otherSpec, currentOption)) {
      console.warn(`【奈雪】⚠️ "${otherSpec.name}:${currentOption.name}" 与当前选择不兼容，自动切换`);
      
      // 找到第一个兼容的选项
      const compatibleOption = otherSpec.options.find(opt => !isOptionDisabled(otherSpec, opt));
      if (compatibleOption) {
        selectedSpecs[otherSpecKey] = getOptionKey(compatibleOption);
        console.log(`【奈雪】✅ 自动切换为 "${otherSpec.name}:${compatibleOption.name}"`);
      }
    }
  });
  
  // 尝试匹配SKU（用于调试）
  if (product.skuList && product.skuList.length > 0) {
    const selectedCount = Object.keys(selectedSpecs).length;
    console.log(`【奈雪】已选 ${selectedCount}/${product.specs.length} 个规格`);
    
    // 如果选择了所有规格，尝试匹配
    if (selectedCount === product.specs.length) {
      console.log('【奈雪】规格选择完整，尝试匹配SKU...');
      const matched = findMatchingSku();
      if (matched) {
        console.log('【奈雪】✅ 匹配成功，SKU:', matched.code);
      } else {
        console.warn('【奈雪】⚠️ 匹配失败，请检查规格选择');
      }
    }
  }
}

// 切换加料
function toggleAccessory(accessory) {
  const index = selectedAccessories.value.indexOf(accessory.code);
  if (index > -1) {
    selectedAccessories.value.splice(index, 1);
  } else {
    selectedAccessories.value.push(accessory.code);
  }
  console.log('【奈雪】当前已选加料:', selectedAccessories.value);
}

// 计算当前价格
const currentPrice = computed(() => {
  let finalPrice = product.basePrice;
  
  // 规格加价
  product.specs.forEach(spec => {
    const specKey = getSpecKey(spec);
    const selectedOptionKey = selectedSpecs[specKey];
    if (!selectedOptionKey) return;
    
    const option = findOption(spec, selectedOptionKey);
    if (option?.price) {
      finalPrice += option.price;
    }
  });
  
  // 加料加价
  selectedAccessories.value.forEach(code => {
    const accessory = product.accessories.find(a => a.code === code);
    if (accessory?.price) {
      finalPrice += accessory.price;
    }
  });
  
  return finalPrice.toFixed(2);
});

// 检查是否有禁用的选项
const hasDisabledOptions = computed(() => {
  return product.specs.some(spec => 
    spec.options.some(option => isOptionDisabled(spec, option))
  );
});

// 加入购物车
// 根据选择的规格匹配SKU
function findMatchingSku() {
  if (!product.skuList || product.skuList.length === 0) {
    console.warn('【奈雪】没有SKU列表');
    return null;
  }
  
  console.log('【奈雪】开始匹配SKU，用户选择:', selectedSpecs);
  console.log('【奈雪】可用SKU数量:', product.skuList.length);
  
  // 获取用户选择的规格数量
  const selectedSpecsCount = Object.keys(selectedSpecs).length;
  
  // 输出所有SKU的规格组合（用于调试）
  console.log('【奈雪】所有可用SKU:');
  product.skuList.forEach((sku, index) => {
    const skuInfo = sku.specs.map(s => `${s.spec_name}`).join(' + ');
    console.log(`  SKU${index + 1}: ${sku.code} - ${skuInfo}`);
  });
  
  // 遍历所有SKU，找到匹配的
  let matchAttempts = 0;
  for (const sku of product.skuList) {
    if (!sku.specs || sku.specs.length === 0) continue;
    
    matchAttempts++;
    
    // 检查当前SKU的所有规格是否都匹配用户选择
    let unmatchedSpecs = [];
    const isMatch = sku.specs.every(skuSpec => {
      const selectedOptionId = selectedSpecs[skuSpec.code];
      const match = selectedOptionId === skuSpec.spec_code;
      
      if (!match) {
        unmatchedSpecs.push(`${skuSpec.name}: 要求${skuSpec.spec_code}, 选择${selectedOptionId}`);
      }
      
      return match;
    });
    
    // 同时检查用户选择的所有规格是否都在SKU中
    const allSelectedInSku = Object.keys(selectedSpecs).every(specCode => {
      return sku.specs.some(skuSpec => skuSpec.code === specCode);
    });
    
    // 调试：输出每次匹配尝试
    if (matchAttempts <= 3) {
      console.log(`【奈雪】尝试匹配SKU ${matchAttempts}: ${sku.code}`);
      console.log(`  isMatch=${isMatch}, allSelectedInSku=${allSelectedInSku}`);
      if (unmatchedSpecs.length > 0) {
        console.log(`  不匹配项:`, unmatchedSpecs.join('; '));
      }
    }
    
    if (isMatch && allSelectedInSku) {
      console.log('【奈雪】✅ 找到匹配的SKU:', sku.code, '价格:', sku.salePrice, '/', sku.price);
      console.log('【奈雪】SKU规格数:', sku.specs.length, '用户选择数:', selectedSpecsCount);
      console.log('【奈雪】SKU规格:', sku.specs.map(s => `${s.name}:${s.spec_name}`).join(', '));
      return sku;
    }
  }
  
  console.log(`【奈雪】尝试了 ${matchAttempts} 个SKU，都不匹配`);
  
  // 详细输出失败原因
  console.warn('【奈雪】❌ 未找到匹配的SKU');
  console.warn('【奈雪】用户选择的规格数量:', selectedSpecsCount);
  console.warn('【奈雪】用户选择详情:', JSON.stringify(selectedSpecs, null, 2));
  
  // 输出第一个SKU的结构作为参考
  if (product.skuList.length > 0 && product.skuList[0].specs) {
    console.warn('【奈雪】参考SKU结构（第一个）:', 
      product.skuList[0].specs.map(s => `${s.code}:${s.name}=${s.spec_code}:${s.spec_name}`).join(', ')
    );
    
    // 对比第一个SKU，找出不匹配的规格
    console.warn('【奈雪】对比分析（以第一个SKU为例）:');
    const firstSku = product.skuList[0];
    firstSku.specs.forEach(skuSpec => {
      const userSelected = selectedSpecs[skuSpec.code];
      const isMatch = userSelected === skuSpec.spec_code;
      console.warn(
        `  ${skuSpec.name}(${skuSpec.code}): ` +
        `SKU要求=${skuSpec.spec_code}(${skuSpec.spec_name}), ` +
        `用户选择=${userSelected}, ` +
        `${isMatch ? '✅匹配' : '❌不匹配'}`
      );
    });
    
    // 检查用户是否选择了SKU中不存在的规格
    Object.keys(selectedSpecs).forEach(userSpecCode => {
      const existsInSku = firstSku.specs.some(skuSpec => skuSpec.code === userSpecCode);
      if (!existsInSku) {
        console.warn(`  ⚠️ 用户选择的规格 ${userSpecCode} 不在SKU中`);
      }
    });
  }
  
  return null;
}

function addToCart() {
  // 找到匹配的SKU
  const matchedSku = findMatchingSku();
  
  if (!matchedSku) {
    uni.showToast({ 
      title: '请选择完整的规格', 
      icon: 'none' 
    });
    return;
  }
  
  // 构建完整的规格对象（包含 id 和 linkId）
  const fullSelectedSpecs = buildFullSelectedSpecs(product.specs, selectedSpecs);
  
  const cartItem = {
    id: product.id,
    name: product.name,
    image: product.image,
    price: parseFloat(currentPrice.value),
    originalPrice: product.originalPrice,  // 保存原价（系统设置）
    skuId: matchedSku.code,  // ✅ 保存SKU ID
    skuPrice: parseFloat(matchedSku.salePrice),  // 保存SKU建议售价
    selectedSpecs: fullSelectedSpecs,
    selectedAccessories: [...selectedAccessories.value],
    specsText: buildSpecsText(product.specs, selectedSpecs),
    brandOt: 8,  // ✅ 奈雪的茶品牌类型
  };

  console.log('【奈雪】加入购物车 - 售价:', cartItem.price, '原价:', cartItem.originalPrice);
  console.log('【奈雪】SKU ID:', matchedSku.code, '规格数据:', JSON.stringify(fullSelectedSpecs, null, 2));
  cateringStore.addToCart(cartItem);

  uni.showToast({ title: '已加入购物车', icon: 'success' });
  setTimeout(() => sheep.$router.back(), 1000);
}
</script>

<style lang="scss" scoped>
@import './common/product-detail.scss';

// 奈雪特有样式
.sku-tip {
  background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
  color: #e65100;
  font-size: 24rpx;
  padding: 16rpx 20rpx;
  border-radius: 10rpx;
  margin-bottom: 30rpx;
  line-height: 1.6;
  border-left: 4rpx solid #ffa726;
}

.spec-group-name {
  .disabled-count {
    color: #999;
    font-size: 24rpx;
    margin-left: 10rpx;
  }
}

.spec-option {
  &.disabled {
    background: #f5f5f5 !important;
    color: #ccc !important;
    border: 1rpx solid #e0e0e0 !important;
    opacity: 0.5;
    position: relative;
    
    &::after {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      width: 100%;
      height: 1rpx;
      background: #ccc;
      transform: translateY(-50%);
    }
    
    .option-name::after {
      content: ' (不可选)';
      font-size: 20rpx;
      color: #f44336;
    }
  }
}
</style>

